package client

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"net/http"
	"os"
	"time"

	"servermerge/internal/model"
)

var (
	httpClient    = &http.Client{Timeout: 20 * time.Second}
	gameServerURL = getenv("GAME_SERVER_URL", "http://localhost:9099")
)

func getenv(k, def string) string {
	if v := os.Getenv(k); v != "" {
		return v
	}
	return def
}

func CallGameServer(ctx context.Context, req model.GameExecuteRequest) (*model.GameExecuteResponse, error) {
	url := gameServerURL + "/api/merge/execute"
	body, _ := json.Marshal(req)
	httpReq, _ := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(body))
	httpReq.Header.Set("Content-Type", "application/json")

	resp, err := httpClient.Do(httpReq)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	if resp.StatusCode >= 300 {
		return nil, errors.New("game server error: " + resp.Status)
	}

	var out model.GameExecuteResponse
	if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
		return nil, err
	}
	return &out, nil
}
